<?php
/**
 * 产品属性模型管理
 * @author cjli
 *
 */
class AttributeModel extends Model
{
  const ATTR_TEXT = 0; //手工录入
  const ATTR_OPTIONAL = 1;//从列表中选择
  const ATTR_TEXTAREA = 2;//多行文本框

  /**
   * 属性录入方式
   * @var array
   */
  static $inputType = array(
  	self::ATTR_TEXT => '手工录入',
  	self::ATTR_OPTIONAL => '从列表中选择',
  	self::ATTR_TEXTAREA => '多行文本框',
  );

  /**
   * 属性值选择方式
   */
  static $attrTypeValues = array(
  	'0' => '唯一属性',
  	'1' => '单选属性',
  	'2' => '复选属性',
	'3' => '复选属性(前台一样)',
  );

	/**
	 * 获取属性类型列表
	 */
	public static function getModelList()
	{
		$modelList = array();
		if(S('model_list')){
			$modelList = S('model_list');
		}else{
			$modeldb = D('model');
			$models = $modeldb->select();
			foreach ($models as $r){
				$modelList[$r['id']] = $r['name'];
			}
			S('model_list', $modelList);
		}
		return $modelList;
	}

/**
 * 获得指定的商品类型下所有的属性分组
 * @param int $model_id 模型ID
 *
 * @return  array
 */
public static function getAttributeGroups($model_id)
{
	$modeldb = D('model');
	$attr_group = $modeldb->where('id='.$model_id)->getField('attr_group');
    $grp = str_replace("\r", '', $attr_group);
    if ($grp)
    {
        return explode("\n", $grp);
    }
    else
    {
        return array();
    }
}

	/**
	 * 获取属性列表
	 * @param int $model_id 模型ID
	 */
	public static function getAdminAttributeList($model_id)
	{
		$language_id = C('language_id');
		$where = array(
			'model_id' => $model_id,
			'attribute_items.language_id' => $language_id,
		);

		$attrdb = D('attribute');
		$attrdb->field('attribute.*, model.name AS model_name,count(attribute_values.id) AS attribute_values_count,attribute_items.*');
		$attrdb->join('attribute_values ON attribute_values.attr_id = attribute.attr_id');
		$attrdb->join('model ON model.id = attribute.model_id');
		$attrdb->join('attribute_items ON attribute_items.attribute_id = attribute.attr_id');
		//$attrdb->order('attribute.sort_order DESC, attribute.attr_id ASC');
		$attrdb->order('attribute.attr_id ASC');
		$attrdb->group('attribute.attr_id');
		$attrdb->where($where);
		$attributeList = $attrdb->select();
		return $attributeList;
	}

	/**
	 * 获取属性列表
	 * @param int $model_id 模型ID
	 * @param array $filter 筛选条件
	 */
	public static function getAttributeList($model_id, $filter = array())
	{
		$language_id = C('language_id');
		$where = array(
			'model_id' => $model_id,
			'attribute_items.language_id' => $language_id,
		);
		if($filter){
			foreach ($filter as $key => $val){
				if($val){
					$where[$key] = $val;
				}
			}
		}

		$attrdb = D('attribute');
		$attrdb->field('attribute.*, model.name AS model_name,attribute_items.*');
//		$attrdb->join('attribute_values ON attribute_values.attr_id = attribute.attr_id');
		$attrdb->join('model ON model.id = attribute.model_id');
		$attrdb->join('attribute_items ON attribute_items.attribute_id = attribute.attr_id');
		$attrdb->order('attribute.sort_order DESC');
		$attrdb->group('attribute.attr_id');
		$attrdb->where($where);
		$attributeList = $attrdb->select();
//		echo $attrdb->getLastSql();exit;
		return $attributeList;
	}

	/**
	 * 属性值列表
	 * @param int $attr_id 属性ID
	 */
	public static function getAttributeValuesList($attr_id)
	{
		$language_id = C('language_id');
		$where = array(
			'attr_id' => $attr_id,
			'attribute_values_items.language_id' => 6,
		);
		$attr_val_db = D('attribute_values');
		$attr_val_db->join('attribute_values_items ON attribute_values_items.att_value_id = attribute_values.id');
		$attr_val_db->where($where);
		$attribute_vals = $attr_val_db->order('sort_order DESC')->select();
		return $attribute_vals;
	}

	/**
	 * 获取属性信息
	 * @param int $attriubte_id 属性ID
	 */
	public static function getAttriubteInfo($attribute_id)
	{
		$attrdb = D('attribute');
		$attribute = $attrdb->find($attribute_id);
		return $attribute;
	}
	/**
	 * 获取身形列表详情
	 * @return array
	 */
	public static function get_user_measure_info($mid)
	{
		$user_measure_db = D('user_measure');
		$measureInfo = $user_measure_db->find($mid);
		return $measureInfo;
	}
	/**
	 * 编辑属性
	 * @param array $post post数据
	 * @param int $attriubte_id 属性ID
	 */
	public static function updateAttriubte($post, $attriubte_id = null)
	{
		$attrdb = D('attribute');
		/* 取得属性信息 */
		$attr = array(
			'model_id'          => intval($post['model_id']),
			'attr_index'      	=> intval($post['attr_index']),
			'attr_sell'			=> intval($post['attr_sell']),
			'attr_input_type' 	=> intval($post['attr_input_type']),
			'attr_type'       	=> intval($post['attr_type']) ,
			'attr_group'     	=> isset($post['attr_group']) ? intval($post['attr_group']) : 0,
			'sort_order'		=> intval($post['sort_order']),
			'attr_advanced'	  	=> intval($post['attr_advanced']),
			'attr_designer' 	=> intval($post['attr_designer']),
			'size_type' 	    => intval($post['size_type']),
			'is_ll' 	   		=> intval($post['is_ll']),
			'is_3d' 	   		=> intval($post['is_3d']),
			'is_show_sd' 	   		=> intval($post['is_show_sd']),
			'is_monogram' 	   		=> intval($post['is_monogram']),
		);
		if(intval($attriubte_id)){
			$attrdb->where('attr_id='. $attriubte_id)->save($attr);
		}else{
			$attriubte_id = $attrdb->add($attr);
		}
		//echo $attrdb->getLastSql();exit;
		S('all_attribute_list', null);
		return $attriubte_id;
	}

	/**
	 * 更新属性内容详细
	 * @param array $post post数据
	 * @param int $pid 产品ID号
	 */
	public static function updateAttributeItems($post, $attribute_id)
	{
		$attributeInfo = self::getAttriubteInfo($attribute_id);
		if(!$attributeInfo) return false;
		$attribute_items_db = D('attribute_items');
		$attribute_items_db->where(array('attribute_id' => $attribute_id))->delete();

		$languageList = SiteModel::getLanguageList();
		foreach($languageList as $language_id => $language_name){
			if($post[$language_id]['name']){
				$data = array(
					'attribute_id' => $attribute_id,
					'language_id' => $language_id,
					'name' => trim($post[$language_id]['name']),
					'attr_content' => trim($post[$language_id]['attr_content']),
				);
				$attribute_items_db->add($data);
			}
		}
	}

	/**
	 * 获取属性值信息
	 * @param int $attriubte_id 属性ID
	 */
	public static function getAttriubteValueInfo($attribute_values_id)
	{
		$attrdb = D('attribute_values');
		$attributeValues = $attrdb->find($attribute_values_id);
		return $attributeValues;
	}

	/**
	 * 更新属性值内容详细
	 * @param array $post post数据
	 * @param int $pid 产品ID号
	 */
	public static function updateAttributeValuesItems($post,$attribute_values_id)
	{
		$attributeValuesInfo = self::getAttriubteValueInfo($attribute_values_id);
		if(!$attributeValuesInfo) return false;
		$attribute_values_items_db = D('attribute_values_items');
		$attribute_values_items_db->where(array('att_value_id' => $attribute_values_id))->delete();

		$languageList = SiteModel::getLanguageList();
		foreach($languageList as $language_id => $language_name){
			if($post[$language_id]['attr_value']){
				$data = array(
					'att_value_id' => $attribute_values_id,
					'language_id' => $language_id,
					'attr_value' => trim($post[$language_id]['attr_value']),
					'attr_content' => trim($post[$language_id]['attr_content']),
				);
				$attribute_values_items_db->add($data);
			}
		}
	}


	/**
	 * 删除属性值
	 * @param int $attr_id 属性ID
	 */
	public static function deleteAttriubteValues($attribute_values_id)
	{
		$attrdb = D('attribute_values');
		$attrdb->delete($attribute_values_id);

		//删除属性详情
		$attribute_values_items_db = D('attribute_values_items');
		$attribute_values_items_db->where(array('att_value_id' => $attribute_values_id))->delete();
	}

	/**
	 * 获取属性内容详细
	 * @param int $pid 产品ID
	 * @param int $language_id 语言ID号
	 */
	public static function getAttributeItems($attribute_id, $language_id = 0)
	{
		$where['attribute_id'] = $attribute_id;
		if($language_id){
			$where['language_id'] = $language_id;
		}
		$attributeItemsArray = array();
		$attribute_items_db = D('attribute_items');
		$attributeItems = $attribute_items_db->where($where)->select();
		if($attributeItems){
			foreach ($attributeItems as $item){
				$attributeItemsArray[$item['language_id']] = $item;
			}
		}
		return $attributeItemsArray;
	}

	/**
	 * 获取属性值内容详细
	 * @param int $pid 产品ID
	 * @param int $language_id 语言ID号
	 */
	public static function getAttributeItemsValues($attribute_values_id, $language_id = 0)
	{
		$where['att_value_id'] = $attribute_values_id;
		if($language_id){
			$where['language_id'] = $language_id;
		}
		$attributeItemsValuesArray = array();
		$attribute_values_items_db = D('attribute_values_items');
		$attributeValuesItems = $attribute_values_items_db->where($where)->select();
		if($attributeValuesItems){
			foreach ($attributeValuesItems as $item){
				$attributeItemsValuesArray[$item['language_id']] = $item;
			}
		}
		return $attributeItemsValuesArray;
	}

	/**
	 * 删除属性
	 * @param int $attr_id 属性ID
	 */
	public static function deleteAttriubte($attr_id)
	{
		$attrdb = D('attribute');
		$attrdb->delete($attr_id);

		//删除属性值
		$attribute_value_db = D('attribute_values');
		$attribute_value_db->where(array('attr_id' => $attr_id))->delete();

		//删除属性详情
		$attribute_items_db = D('attribute_items');
		$attribute_items_db->where(array('attribute_id' => $attr_id))->delete();

		//删除产品关联属性
		$product_attribute_db = D('product_attribute');
		$product_attribute_db->where(array('attr_id' => $attr_id))->delete();
		S('all_attribute_list', null);
	}

	/**
   * 返回属性值html显示类型
   * @param array $attribute 属性数组信息
   * @param int $pid 产品ID
   * @return string
   */
	public static function getAttributeValuesHtml($model_id, $pid, $did=0)
	{
		$product_attribute_db = D('product_attribute');

		$html = '<table width="100%" id="attrTable">';
		$spec = 0;
		$attributeList = self::getAttributeList($model_id);
		if($attributeList)
		{
			foreach ($attributeList as $attribute)
			{
				$attribute_id = $attribute['attr_id'];

				 //属性值列表
				$attributeValuesList = self::getAttributeValuesList($attribute_id);

				//Input 名称
				$fieldName = 'field_' . $attribute_id;
				//默认信息
				$defaultValue = array();
                $is_default = array();
				if($did){
					$product_attribute_db->where(array('attr_id'=>$attribute_id, 'designer_id'=>$did));
			 		$productAttributeList = $product_attribute_db->select();
			 		//多值
			 		if($attribute['attr_type'] >= 2){
			 			foreach ($productAttributeList as $key => $val){
			 				if($val['is_default']){
                                 $is_default[] = $val['is_default'];
			 				}
			 				if($attribute['attr_input_type']==0){
			 					$defaultValue[] = $val['attr_value'];
			 				}else{
			 					$defaultValue[$val['attr_value_id']] = $val;
			 				}
			 			}
			 		}else{
			 			$defaultValue = $productAttributeList ? reset($productAttributeList) : null;
			 		}
				}else{
					if($pid){
	//			 		$product_attribute_db->field('attr_value_id,attr_value');
						$product_attribute_db->where(array('attr_id'=>$attribute_id, 'product_id'=>$pid));
						$productAttributeList = $product_attribute_db->select();
						//多值
						if($attribute['attr_type'] >=2){
							foreach ($productAttributeList as $key => $val){
                                if ($val['is_default']) {
                                    $is_default[] = $val['is_default'];
                                }
								if($attribute['attr_input_type']==0){
									$defaultValue[] = $val['attr_value'];
								}else{
									$defaultValue[$val['attr_value_id']] = $val;
								}
							}
						}else{
							$defaultValue = $productAttributeList ? reset($productAttributeList) : null;
						}
					}
				}


				//手工录入
				if($attribute['attr_input_type']==0)
				{
					//单选
		      	if($attribute['attr_type'] == 1)
		      	{
		      		$html .= "<tr><td class='label' width=\"150\">".$attribute['name']."</td><td>";
		        	$html .= '<input type="text" class="input-text" name="' . $fieldName . '" value="' . isset($defultValue['attr_value']) ? $defultValue['attr_value'] : null . '"></td></tr>';
		      	}
		      	else	//多选
		      	{
		      		if($defaultValue){
			      		foreach ($defaultValue as $default_val){
				         	$html .= "<tr><td class='label' width=\"150\">";
						 			$html .= ($spec != $attribute_id) ? "<a href='javascript:;' onclick='addSpec(this)'>[+]</a>" : "<a href='javascript:;' onclick='removeSpec(this)'>[-]</a>";
						 			$html .= $attribute['name']."</td><td>";
						 			$html .= '<input type="text"  class="input-text" name="' . $fieldName . '[]" value="' . (isset($default_val) ? $default_val : null) . '"></td></tr>';
						 			$spec = $attribute_id;
			      		}
		      		}else{
		      			$html .= "<tr><td class='label' width=\"150\">";
						 		$html .= ($spec != $attribute_id) ? "<a href='javascript:;' onclick='addSpec(this)'>[+]</a>" : "<a href='javascript:;' onclick='removeSpec(this)'>[-]</a>";
						 		$html .= $attribute['name']."</td><td>";
						 		$html .= '<input type="text"  class="input-text" name="' . $fieldName . '[]" value=""></td></tr>';
						 		$spec = $attribute_id;
		      		}
		      	}
				}
				//列表选择
				elseif($attribute['attr_input_type']==1 && $attributeValuesList)
				{
					$html .= "<tr><td class='label' width=\"150\">".$attribute['name']."</td><td id='td_attr_cols_".$attribute_id."'>全选<input type='checkbox' class='rows_attr_check' value='".$attribute_id."'>";
		      	foreach ($attributeValuesList as $fvalue)
		      	{
		      		$attribute_values_id = isset($defaultValue[$fvalue['id']]) ? $fvalue['id'] : null;
                    $html .= '<div data-attr-id="'.$attribute_id.'" class="attr_value' . (in_array($fvalue['id'], $is_default) ? ' is_default' : '') . '">';
		      		//显示图片
		      		if($fvalue['attr_img']){
		      			$html .= '<img src="'.$fvalue['attr_img'].'" width="50" height="50"/><br/>';
		      		}
					//单选
					if($attribute['attr_type'] == 1)
					{
						$html .= '<label><input name="' . $fieldName . '[]" type="radio" value="' . $fvalue['id'] . '"' . ($fvalue['id'] == $defaultValue['attr_value_id'] ? ' checked="checked"' : '') . '> </label>';
					}else{//多选
						$html .= '<label><input name="' . $fieldName . '[]" type="checkbox" value="' . $fvalue['id'] . '"' . ($fvalue['id'] == $attribute_values_id ? ' checked="checked"' : '') . '> </label>';
					}
					$html .=  $fvalue['attr_value'] . '</div>';
		       }
		       $html .='<input type="hidden" name="' . $fieldName . '[default]" value="' . implode(',', $is_default) . '">';
		       $show_attr_array=array();
			   if($pid){
				 
			  	 	$product=D('product')->field("show_attr_ids,show_thread_color")->where(array("id"=>$pid))->find();
				 	if($product['show_attr_ids']){
						$show_attr_array=explode(",",$product['show_attr_ids']);
					}
			   }
			   $html .='<select name="show_attr_ids[]"><option value="1_'.$attribute_id.'">不显示</option><option value="2_'.$attribute_id.'" ';
			   if(in_array($attribute_id,$show_attr_array)){
				   $html .=' selected="selected" ';
			   }else{
				   	if(!$pid){
						if($attribute['is_ll']==2){
							$html .=' selected="selected" ';
						}
					}
			   }
			   $html .='>显示</option></select>';
			   if(in_array($attribute['attr_id'],array(57,72,114))){
				   if($pid){
					   if($product['show_thread_color']==1){
						   $html .='&nbsp;&nbsp;&nbsp;<select name="show_thread_color"><option value="1" selected="selected">所有的扣眼线</option><option value="2">插花眼和袖口最后一个扣眼</option></select>';
					   }else{
						    $html .='&nbsp;&nbsp;&nbsp;<select name="show_thread_color"><option value="1">所有的扣眼线</option><option value="2" selected="selected">插花眼和袖口最后一个扣眼</option></select>';
					   }
				   }else{
					   $html .='&nbsp;&nbsp;&nbsp;<select name="show_thread_color"><option value="1">所有的扣眼线</option><option value="2" selected="selected">插花眼和袖口最后一个扣眼</option></select>';
				   }
			   }
		       $html .= '</td></tr>';
				}
			}
    }
    $html .= '</table>';
    return $html;
	}

/**
   * 返回作品属性值html显示类型
   * @param array $attribute 属性数组信息
   * @param int $designer_pid 作品ID
   * @return string
   */
	public static function getDesignerAttributeValuesHtml($model_id, $designer_pid)
	{
		$user_designer_product_db = D('user_designer_product');
		$html = '<table width="100%" id="attrTable">';
		$spec = 0;

		//作品属性
		if($designer_pid){
	 		$user_designer_product_db->field('attr');
	 		$user_designer_product_db->where(array('designer_product_id'=>$designer_pid));
	 		$attr = $user_designer_product_db->getField('attr');
	 		if($attr){
	 			$productAllAttributeList = unserialize($attr);
	 		}
		}

		$attributeList = self::getAttributeList($model_id, array('attr_designer' => 1));
		if($attributeList)
		{
			foreach ($attributeList as $attribute)
			{
				$attribute_id = $attribute['attr_id'];

				 //属性值列表
				$attributeValuesList = self::getAttributeValuesList($attribute_id);

				//Input 名称
				$fieldName = 'field_' . $attribute_id;
				//默认信息
				$defaultValue = array();
				$is_default = 0;

				$productAttributeList = $productAllAttributeList;
				if($productAttributeList){
					foreach ($productAttributeList as $key => $val){
						if($val['attr_id'] != $attribute_id){
							unset($productAttributeList[$key]);
						}
					}
			 		//多值
			 		if($attribute['attr_type'] == 2){
			 			foreach ($productAttributeList as $key => $val){
			 				if($val['is_default']){
			 					$is_default = $val['is_default'];
			 				}
			 				if($attribute['attr_input_type']==0){
			 					$defaultValue[] = $val['attr_value'];
			 				}else{
			 					$defaultValue[$val['attr_value_id']] = $val;
			 				}
			 			}
			 		}else{
			 			$defaultValue = $productAttributeList ? reset($productAttributeList) : null;
			 		}
		 		}
//		dump($defaultValue);exit;
		//手工录入
				if($attribute['attr_input_type']==0)
				{
					//单选
		      	if($attribute['attr_type'] == 1)
		      	{
		      		$html .= "<tr><td class='label' width=\"150\">".$attribute['name']."</td><td>";
		        	$html .= '<input type="text" class="input-text" name="' . $fieldName . '" value="' . isset($defultValue['attr_value']) ? $defultValue['attr_value'] : null . '"></td></tr>';
		      	}
		      	else	//多选
		      	{
		      		if($defaultValue){
			      		foreach ($defaultValue as $default_val){
				         	$html .= "<tr><td class='label' width=\"150\">";
						 			$html .= ($spec != $attribute_id) ? "<a href='javascript:;' onclick='addSpec(this)'>[+]</a>" : "<a href='javascript:;' onclick='removeSpec(this)'>[-]</a>";
						 			$html .= $attribute['name']."</td><td>";
						 			$html .= '<input type="text"  class="input-text" name="' . $fieldName . '[]" value="' . (isset($default_val) ? $default_val : null) . '"></td></tr>';
						 			$spec = $attribute_id;
			      		}
		      		}else{
		      			$html .= "<tr><td class='label' width=\"150\">";
						 		$html .= ($spec != $attribute_id) ? "<a href='javascript:;' onclick='addSpec(this)'>[+]</a>" : "<a href='javascript:;' onclick='removeSpec(this)'>[-]</a>";
						 		$html .= $attribute['name']."</td><td>";
						 		$html .= '<input type="text"  class="input-text" name="' . $fieldName . '[]" value=""></td></tr>';
						 		$spec = $attribute_id;
		      		}
		      	}
				}
				//列表选择
				elseif($attribute['attr_input_type']==1 && $attributeValuesList)
				{
					$html .= "<tr><td class='label' width=\"150\">".$attribute['name']."</td><td>";
		      	foreach ($attributeValuesList as $fvalue)
		      	{
		      		$attribute_values_id = isset($defaultValue[$fvalue['id']]) ? $fvalue['id'] : null;

		      		$html .='<div class="attr_value'.($is_default==$fvalue['id'] ? ' is_default' : '').'">';
		      		//显示图片
		      		if($fvalue['attr_img']){
		      			$html .= '<img src="'.$fvalue['attr_img'].'" width="50" height="50"/><br/>';
		      		}
		      		//单选
				      if($attribute['attr_type'] == 1)
				      {
				      	$html .= '<label><input name="' . $fieldName . '[]" type="radio" value="' . $fvalue['id'] . '"' . ($fvalue['id'] == $attribute_values_id ? ' checked="checked"' : '') . '> </label>';
				      }else{//多选
				      	$html .= '<label><input name="' . $fieldName . '[]" type="checkbox" value="' . $fvalue['id'] . '"' . ($fvalue['id'] == $attribute_values_id ? ' checked="checked"' : '') . '> </label>';
				      }
				      $html .=  $fvalue['attr_value'] . '</div>';
		       }
		       $html .='<input type="hidden" name="' . $fieldName . '[default]" value="'.$is_default.'">';
		       $html .= '</td></tr>';
				}
			}
    }
    $html .= '</table>';
    return $html;
	}
public function getAttributevalue($language_id){
        $user = D('attribute_items')->where('language_id = '.$language_id)->find();
        $user_info = D('attribute_values_items')->where('language_id = '.$language_id)->find();
}

}